package com.school.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.school.entity.HljtDevice;
import com.school.entity.HljtSetting;
import com.school.entity.HljtVersion;
import com.school.entity.android.Equipment;
import com.school.entity.android.WithTheNew;
import com.school.entity.web.HljtDeviceManagement;
import com.school.service.HljtOtherInterfacesService;
import com.school.util.JsonInterface;
import com.school.service.impl.HljtDeviceServiceImpl;
import com.school.util.JsonUtil;
import com.school.util.PictureVideoUpload;
import com.school.util.RepUtil;
import com.school.util.WhetherNotToUpdate;

import net.dongliu.apk.parser.ApkFile;
import net.sf.json.JSONArray;

@Controller
public class HljtOtherInterfacesController {
	@Autowired
	private HljtOtherInterfacesService hljtOtherInterfacesService;
	@Autowired
	private HljtDeviceServiceImpl hljtDeviceServiceImpl;
	/**
	 * 数据是否有更新
	 * @param hljtDevice
	 * @param jsonUtil
	 * @return
	 */
	@RequestMapping("/withTheNew")
	@ResponseBody
	public JSONObject withTheNew(HljtDevice hljtDevice,JsonUtil jsonUtil,String type) {
		try {
			if(null !=hljtDevice.getMac()) {
				Map<String, Object> temp = 	hljtOtherInterfacesService.withTheNew(hljtDevice , type);
				HljtDevice d = (HljtDevice) temp.get("hljtDevice");
				if(null !=d) {
					if(null !=d.getClassid()) {
						WithTheNew te =(WithTheNew) temp.get("withTheNew");
						hljtDevice.setEndtime(new Date());
						hljtDevice.setState(2);
						hljtDeviceServiceImpl.updateDevice(hljtDevice);
						if(null != te) {
								jsonUtil.setSucceed(JSON.toJSONString(te) ,"数据有更新");
						}else {
							jsonUtil.setSucceed(JSON.toJSONString(null), "数据最新");
						}
					}else {
						jsonUtil.setnotClassId("没有添加班级id");
					}
				}else {
					jsonUtil.setnotMac("没有添加Mac");
				}
			}else {
				jsonUtil.setFailMsg("参数错误");
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsonUtil.setServerException("服务器异常");
		}
		System.out.println("withTheNew"+jsonUtil.toJSONString()+"mac,"+hljtDevice.getMac());
		return jsonUtil.toJSONString();
	}
	
	/**
	 * 设备开机时间
	 * @param hljtDevice
	 * @param jsonUtil
	 * @return
	 */
	@RequestMapping("/switchTime")
	@ResponseBody
	public JsonInterface switchTime(String mac) {
		JsonInterface jsonInterface=new JsonInterface();
		HljtSetting setting = hljtOtherInterfacesService.switchTime();
		HljtDevice f = hljtDeviceServiceImpl.allDeviceMacManualStarupTime(mac);
		if(null != setting || null != f) {
			List<Equipment> listequipment =this.getEquipment();
			Equipment g = new Equipment();
			g.setWeek(8+"");
			Map<String , Object>ff = this.carriedOut(mac, f);
			if(null!=f &&null!= f.getManualstaruptime()&& null != ff && (boolean)ff.get(mac+"true")) {
				g.setBoottime(f.getManualstaruptime().getTime()+"");
				g.setDevice(1+"");
			}else {
				g.setBoottime(null);
				g.setDevice(0+"");
			}
			listequipment.add(g);
			
			JSONArray array=JSONArray.fromObject(listequipment);
			jsonInterface.setData(array.toString());
			jsonInterface.setErrCode(0);
			jsonInterface.setErrMsg("请求成功");
			
		}else{
			jsonInterface.setErrCode(1);
			jsonInterface.setErrMsg("无数据，请添加数据！");
		}
		return jsonInterface;
	}
	public List<Equipment> getEquipment() {
		HljtSetting setting = hljtOtherInterfacesService.switchTime();
		List<Equipment> listequipment=new ArrayList<>();
		if(null!=setting) {
			for(int i=0;i<7;i++) {
				if(i==0) {
					//7
					Equipment equipment=new Equipment();
					equipment.setWeek(i+1+"");
					equipment.setBoottime(setting.getSunday_DeviceBootTime());
					equipment.setShutdown(setting.getSunday_DeviceShutdown());
					equipment.setDevice(setting.getSunday_Device());
					listequipment.add(equipment);
					
				}else if(i==1) {
					//1
					Equipment equipment=new Equipment();
					equipment.setWeek(i+1+"");
					equipment.setBoottime(setting.getMonday_DeviceBootTime());
					equipment.setShutdown(setting.getMonday_DeviceShutdown());
					equipment.setDevice(setting.getMonday_Device());
					listequipment.add(equipment);
					
				}else if(i==2) {
					//2
					Equipment equipment=new Equipment();
					equipment.setWeek(i+1+"");
					equipment.setBoottime(setting.getTuesday_DeviceBootTime());
					equipment.setShutdown(setting.getTuesday_DeviceShutdown());
					equipment.setDevice(setting.getTuesday_Device());
					listequipment.add(equipment);
					
				}else if(i==3) {
					//3
					Equipment equipment=new Equipment();
					equipment.setWeek(i+1+"");
					equipment.setBoottime(setting.getWednesday_DeviceBootTime());
					equipment.setShutdown(setting.getWednesday_DeviceShutdown());
					equipment.setDevice(setting.getWednesday_Device());
					listequipment.add(equipment);
					
				}else if(i==4) {
					//4
					Equipment equipment=new Equipment();
					equipment.setWeek(i+1+"");
					equipment.setBoottime(setting.getThursday_DeviceBootTime());
					equipment.setShutdown(setting.getThursday_DeviceShutdown());
					equipment.setDevice(setting.getThursday_Device());
					listequipment.add(equipment);
					
				}else if(i==5) {
					//5
					Equipment equipment=new Equipment();
					equipment.setWeek(i+1+"");
					equipment.setBoottime(setting.getFriday_DeviceBootTime());
					equipment.setShutdown(setting.getFriday_DeviceShutdown());
					equipment.setDevice(setting.getFriday_Device());
					listequipment.add(equipment);
				
				}else if(i==6) {
					//6
					Equipment equipment=new Equipment();
					equipment.setWeek(i+1+"");
					equipment.setBoottime(setting.getSaturday_DeviceBootTime());
					equipment.setShutdown(setting.getSaturday_DeviceShutdown());
					equipment.setDevice(setting.getSaturday_Device());
					listequipment.add(equipment);
				}
			}
		}else {
			Equipment equipment=new Equipment();
			listequipment.add(equipment);
		}
		
		
		
		return listequipment;
	}
	
	
	
	Map<String, Object>mapDateSwitchTime = new HashMap<>();
	public Map<String, Object> carriedOut(String mac , HljtDevice f){
		if(null!=f) {
			if(mapDateSwitchTime.containsKey(mac)) {
				Long ls = (Long) mapDateSwitchTime.get(mac+"manualstaruptime");
				if(null == f.getManualstaruptime() || ls ==f.getManualstaruptime().getTime()) {
					mapDateSwitchTime.put(mac+"true", false);
				}else {
					mapDateSwitchTime.put(mac+"true", true);
					mapDateSwitchTime.put(mac+"manualstaruptime", f.getManualstaruptime().getTime());
				}
			}else {
				if(null!=f.getManualstaruptime()) {
					mapDateSwitchTime.put(mac+"true", true);
					mapDateSwitchTime.put(mac+"manualstaruptime", f.getManualstaruptime().getTime());
				}else {
					mapDateSwitchTime.put(mac+"true", false);
					mapDateSwitchTime.put(mac+"manualstaruptime", 0L);
				}
				mapDateSwitchTime.put(mac, mac);
			}
		}
		return mapDateSwitchTime;
		
	}
	
	
	
	
	
	
	
	/**
	 * 保存升级包
	 * @param hljtSchoolimage
	 * @param jsonUtil
	 * @return
	 */
	@RequestMapping("/addVersionPackage")
	@ResponseBody
	public JSONObject addVersionPackage(HttpServletResponse rep , HttpServletRequest request,JsonUtil jsonUtil) {
		JSONObject ret=new JSONObject();
		try {
			RepUtil.repPake(rep);
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			 MultipartFile file=null;
			if (isMultipart){ 
			    MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
			     file = multipartRequest.getFile("imgFile");
			     if(".apk".equals(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")))){
			    	 String imagePath = PictureVideoUpload.savePictureVideo(file, WhetherNotToUpdate.getSaveDisk());
			    	 try {
			    		 ApkFile apk = new ApkFile(WhetherNotToUpdate.getSaveDiskApk()+imagePath);
					     if("com.example.class_card".equals(apk.getApkMeta().getPackageName())) {
					    	 HljtVersion hljtVersion = new HljtVersion();
					    	 hljtVersion.setPacketAddress(imagePath);
					    	 hljtVersion.setVersionCode(apk.getApkMeta().getVersionCode()+"");
					    	 hljtVersion.setVersionName(apk.getApkMeta().getVersionName());
					    	 ret.put("Success", hljtOtherInterfacesService.addHljtVersion(hljtVersion));
					     }else {
					    	 ret.put("ErrPackage", "请检查升级包是否是安卓应用的apk");
					    	 ret.put("Success", false);
					     }
					} catch (Exception e) {
						e.printStackTrace();
						 ret.put("ErrPackage", "请检查升级包是否是安卓应用的apk");
				    	 ret.put("Success", false);
					}
			     }else {
			    	 ret.put("ErrPackage", "升级包.apk结尾");
			    	 ret.put("Success", false);
			     }
			}else {
				ret.put("ErrPackage", "请上传升级包");
				 ret.put("Success", false);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ret.put("serverException", "服务器异常");
			 ret.put("Success", false);
		}
		return ret;
	}
	
	
	
	
	
	
	/**
	 * 查找版本是否有跟新的设备
	 * @param hljtSchoolimage
	 * @param jsonUtil
	 * @return
	 */
	@RequestMapping("/deviceUpgradeInfo")
	@ResponseBody
	public JSONObject deviceUpgradeInfo( Integer pageSize , Integer pageIndex , HttpServletResponse rep , HttpServletRequest request,JsonUtil jsonUtil) {
		JSONObject ret=new JSONObject();
		try {
			RepUtil.repPake(rep);
			 ret.put("data", hljtOtherInterfacesService.deviceUpgradeInfo(pageSize, pageIndex));
		} catch (Exception e) {
			e.printStackTrace();
			ret.put("serverException", "服务器异常");
		}
		return ret;
	}
	
	
	
	/**
	 * 需要升级的设备修改状态
	 * @param hljtSchoolimage
	 * @param jsonUtil
	 * @return
	 */
	@RequestMapping("/needupgradeDevice")
	@ResponseBody
	public JSONObject needupgradeDevice( String data , HttpServletResponse rep , HttpServletRequest request,JsonUtil jsonUtil) {
		JSONObject ret=new JSONObject();
		try {
			RepUtil.repPake(rep);
			List<HljtDeviceManagement> list = JSON.parseArray(data, HljtDeviceManagement.class);
			 ret.put("Success", hljtOtherInterfacesService.needupgradeDevice(list));
		} catch (Exception e) {
			e.printStackTrace();
			ret.put("Success", false);
			ret.put("serverException", "服务器异常");
		}
		return ret;
	}
	
}
